import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_test1/constant/event.dart';
import 'package:flutter_test1/utils/eventBus.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class WebView extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return _WebView();
  }
}

class _WebView extends State<WebView>{

  FlutterWebviewPlugin _webviewPlugin = FlutterWebviewPlugin();

  @override
  void initState() {
    super.initState();

    _webviewPlugin.onStateChanged.listen((event) {
      debugPrint("开始加载-----${event.type}");
      switch (event.type) {
        case WebViewState.startLoad: // 开始加载
          debugPrint("开始加载");
          break;
        case WebViewState.finishLoad: // 加载结束
          debugPrint("加载结束");
          _webviewPlugin.evalJavascript("finishLoad('flutter调用js')");
          break;
        default:
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("webView"),
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Icon(Icons.arrow_back_ios),
        ),
        centerTitle: true,
        automaticallyImplyLeading: false,
      ),
      body: WebviewScaffold(
        url: getAssetsPath("assets/show.html"),
        clearCache: true,
        javascriptChannels: [
          _toastJsChannel(context),
          _setTitleJsChannel(context),
        ].toSet(),
      ),
    );
  }

  @override
  void dispose() {
    _webviewPlugin.dispose();
    super.dispose();
  }


  // 创建 JavascriptChannel
  JavascriptChannel _toastJsChannel(BuildContext context) => JavascriptChannel(
    name: 'Toast',
    onMessageReceived: (JavascriptMessage message) {
      print(message.message);
      EasyLoading.showToast(message.message);
    }
  );
  JavascriptChannel _setTitleJsChannel(BuildContext context) => JavascriptChannel(
      name: 'SetTitle',
      onMessageReceived: (JavascriptMessage message) {
        print(message.message);
        MyEventBus.instance.fireEventData<String>(EVENT_FORM,
            childType: EVENT_SET_MINE_TITLE,data: message.message);
      }
  );

  ///获取打包后的资源文件实际路径
  ///如assets/files/index.html
  String getAssetsPath(String path) {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return 'file:///android_asset/flutter_assets/' + path;
    } else {
      return 'file://Frameworks/App.framework/flutter_assets/' + path;
    }
  }
}